<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\scanwork\Config as ConfigModel;
use think\Db;
use fast\Http;
use think\facade\Config;

/**
 * 微信小程序报工接口
 */
class Wbg extends Api
{
    protected $noNeedLogin = ['login', 'bind'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信登录
     */
    public function login()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('缺少参数code');
        }

        // 获取微信用户信息
        $appid = ConfigModel::getMiniappAppid();
        $appsecret = ConfigModel::getMiniappSecret();
        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
        $result = Http::get($url);
        $wxResult = json_decode($result, true);
        
        if (isset($wxResult['errcode'])) {
            $this->error('微信登录失败: ' . $wxResult['errmsg']);
        }
        
        $openid = $wxResult['openid'];
        $sessionKey = $wxResult['session_key'];
        
        // 查找用户
        $user = Db::name('user')->where(['wx_openid' => $openid])->find();
        
        if (!$user) {
            // 创建新用户
            $data = [
                'username' => 'wx_' . uniqid(),
                'nickname' => '微信用户',
                'password' => '',
                'salt' => '',
                'email' => '',
                'mobile' => '',
                'avatar' => '',
                'level' => 1,
                'gender' => 0,
                'birthday' => '',
                'bio' => '',
                'money' => 0,
                'score' => 0,
                'successions' => 1,
                'maxsuccessions' => 1,
                'prevtime' => time(),
                'logintime' => time(),
                'loginip' => $this->request->ip(),
                'loginfailure' => 0,
                'joinip' => $this->request->ip(),
                'jointime' => time(),
                'wx_openid' => $openid,
                'status' => 'normal'
            ];
            
            $userId = Db::name('user')->insertGetId($data);
            $user = Db::name('user')->where(['id' => $userId])->find();
        }
        
        // 更新登录信息
        Db::name('user')->where(['id' => $user['id']])->update([
            'prevtime' => $user['logintime'],
            'logintime' => time(),
            'loginip' => $this->request->ip(),
            'loginfailure' => 0
        ]);
        
        // 设置Token
        $token = Random::uuid();
        Token::set($token, $user['id'], 2592000);
        $userInfo = Db::name('user')->where(['id' => $user['id']])->find();
        
        $this->success('登录成功', [
            'userInfo' => $userInfo,
            'token' => $token
        ]);
    }

    /**
     * 绑定已有账户
     */
    public function bind()
    {
        $code = $this->request->post('code');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        
        if (!$code || !$username || !$password) {
            $this->error('参数不完整');
        }
        
        // 获取微信用户信息
        $appid = ConfigModel::getMiniappAppid();
        $appsecret = ConfigModel::getMiniappSecret();
        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
        $result = Http::get($url);
        $wxResult = json_decode($result, true);
        
        if (isset($wxResult['errcode'])) {
            $this->error('微信登录失败: ' . $wxResult['errmsg']);
        }
        
        $openid = $wxResult['openid'];
        
        // 验证用户账户
        $user = Db::name('user')->where(['username' => $username])->find();
        
        if (!$user) {
            $this->error('用户不存在');
        }
        
        if ($user['password'] != md5(md5($password) . $user['salt'])) {
            $this->error('密码错误');
        }
        
        // 检查是否已绑定其他微信账户
        $existingUser = Db::name('user')->where(['wx_openid' => $openid])->find();
        if ($existingUser && $existingUser['id'] != $user['id']) {
            $this->error('该微信账户已绑定其他账号');
        }
        
        // 绑定微信账户
        Db::name('user')->where(['id' => $user['id']])->update([
            'wx_openid' => $openid
        ]);
        
        // 更新登录信息
        Db::name('user')->where(['id' => $user['id']])->update([
            'prevtime' => $user['logintime'],
            'logintime' => time(),
            'loginip' => $this->request->ip(),
            'loginfailure' => 0
        ]);
        
        // 设置Token
        $token = Random::uuid();
        Token::set($token, $user['id'], 2592000);
        
        $userInfo = Db::name('user')->where(['id' => $user['id']])->find();
        
        $this->success('绑定成功', [
            'userInfo' => $userInfo,
            'token' => $token
        ]);
    }

    /**
     * 修改用户信息
     */
    public function updateProfile()
    {
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $password = $this->request->post('password');
        $oldPassword = $this->request->post('oldPassword');
        
        $data = [];
        
        // 修改用户名
        if ($username && $username != $this->auth->username) {
            $exist = Db::name('user')->where(['username' => $username])->find();
            if ($exist) {
                $this->error('用户名已被占用');
            }
            $data['username'] = $username;
        }
        
        // 修改昵称
        if ($nickname && $nickname != $this->auth->nickname) {
            $data['nickname'] = $nickname;
        }
        
        // 修改密码
        if ($password) {
            if (!$oldPassword) {
                $this->error('请输入原密码');
            }
            
            if ($this->auth->password != md5(md5($oldPassword) . $this->auth->salt)) {
                $this->error('原密码错误');
            }
            
            $salt = Random::alnum();
            $newPassword = md5(md5($password) . $salt);
            $data['password'] = $newPassword;
            $data['salt'] = $salt;
        }
        
        if (!empty($data)) {
            Db::name('user')->where(['id' => $this->auth->id])->update($data);
        }
        
        $userInfo = Db::name('user')->where(['id' => $this->auth->id])->find();
        
        $this->success('更新成功', ['userInfo' => $userInfo]);
    }

    /**
     * 获取报工记录
     */
    public function getReports()
    {
        $reports = Db::name('scanwork_report')
            ->where(['user_id' => $this->auth->id])
            ->order('createtime desc')
            ->select();
            
        $this->success('', null, $reports);
    }

    /**
     * 获取工资统计
     */
    public function getWageStats()
    {
        $totalQuantity = Db::name('scanwork_report')
            ->where(['user_id' => $this->auth->id, 'status' => 1])
            ->sum('quantity');
            
        $totalWage = Db::name('scanwork_report')
            ->where(['user_id' => $this->auth->id, 'status' => 1])
            ->sum('wage');
            
        $confirmedWage = Db::name('scanwork_report')
            ->where(['user_id' => $this->auth->id, 'status' => 1])
            ->sum('wage');
            
        $pendingWage = Db::name('scanwork_report')
            ->where(['user_id' => $this->auth->id, 'status' => 0])
            ->sum('wage');
            
        $this->success('', null, [
            'total_quantity' => $totalQuantity ?: 0,
            'total_wage' => $totalWage ?: 0,
            'confirmed_wage' => $confirmedWage ?: 0,
            'pending_wage' => $pendingWage ?: 0
        ]);
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $userInfo = Db::name('user')
            ->where(['id' => $this->auth->id])
            ->find();
            
        $this->success('', null, $userInfo);
    }
}